package com.sdx.console.crm.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.service.RedisService;
import com.sdx.console.crm.entity.CrmMessage;
import com.sdx.console.crm.entity.CrmRepresentive;
import com.sdx.console.crm.entity.CrmSession;
import com.sdx.console.crm.service.CrmChatService;
import com.sdx.console.crm.service.CrmRepresentiveService;
import com.sdx.console.crm.service.CrmSessionService;
import com.sdx.console.crm.thread.RepresentiveMessageScanner;
import com.sdx.console.customer.entity.CustomerInfo;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName: ChatController
 * @Description:
 * @author: kangbin
 * @date: 2019/6/4 11:03
 */
@RequestMapping("/crm/chat")
@Controller
public class CrmChatController extends AuthorizedBaesController {

    private static final Logger log = LoggerFactory.getLogger(CrmChatController.class);
    private static final String MODEL = "/crm/chat";

    private static final String SQL = "crm.chat";

    //客户等待队列:1
    private static final String WAIT_QUEUE = "_crm_session_wait";

    @Autowired
    private SQLManager sqlManager;

    @Resource
    private RedisService redisService;

    @Autowired
    private CrmSessionService crmSessionService;

    @Autowired
    private CrmRepresentiveService crmRepresentiveService;

    @Autowired
    private CrmChatService crmChatService;


    @GetMapping("/chatLog.do")
    @Function("crm.chat.query")
    @ResponseBody
    public ModelAndView chatLog() {
        ModelAndView view = new ModelAndView(MODEL + "/chatlog.html");
        view.addObject("jsVer", System.currentTimeMillis());
        return view;
    }

    @GetMapping("/index.do")
    @Function("customer.chat.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL + "/index.html");
        view.addObject("jsVer", System.currentTimeMillis());
        CoreUser user = getLoginUser(request);
        view.addObject("userId", user.getId());
        view.addObject("waitQueueSize",redisService.listOpsSize("list" + WAIT_QUEUE +"_"+user.getTenantId()));
        return view;
    }


    @RequestMapping("/getList.json")
    @ResponseBody
    public JsonResult getList(HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        JSONObject json = new JSONObject();
        JSONObject mine = new JSONObject();
        mine.put("username", user.getName());
        mine.put("id", user.getId());
        mine.put("status", "online");
        mine.put("sign", "在深邃的编码世界，做一枚轻盈的纸飞机");
        mine.put("avatar", "http://static.51sdx.com/p/html/kefu/kefu.png");
        json.put("mine", mine);
        return JsonResult.success(json);
    }

    /**
     * 手动接入客户
     * @param request
     * @return
     */
    @RequestMapping("/getCus.json")
    @ResponseBody
    public JsonResult getCus(HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        return getJsonResult(user);
    }

    public JsonResult getJsonResult(CoreUser user) {
        int userId = user.getId().intValue();
        crmChatService.updateCrmRepresentive(userId,"1,2");
        Long waitQueueSize = redisService.listOpsSize("list" + WAIT_QUEUE +"_" +user.getTenantId());
        if(waitQueueSize==0){
            return JsonResult.success();
        }
        Object object = redisService.bFirstOut("list" + WAIT_QUEUE +"_" +user.getTenantId(), 10);
        JSONObject json = new JSONObject();
        try {
           json =  JSON.parseObject(object.toString());
        }catch (Exception e){
            //异常自动取下一条数据
             redisService.removeMember("set" + WAIT_QUEUE +"_" +user.getTenantId(), JSON.toJSONString(object));
             return getJsonResult(user);
        }
        Map<String, Object> map = new HashMap<>();
        String customerId = json.getString("customerId");
        String openid = json.getString("openid");
        map.put("customerId", customerId);
        map.put("openid", openid);
        if (StringUtils.isNotBlank(customerId)) {
            redisService.removeMember("set" + WAIT_QUEUE +"_" +user.getTenantId(), customerId);
        } else {
            redisService.removeMember("set" + WAIT_QUEUE +"_" +user.getTenantId(), openid);
        }
        CustomerInfo customerInfo = sqlManager.selectSingle(SQL + ".findCustomerInfo", map, CustomerInfo.class);

        int sessionId = crmSessionService.insertSession(json, userId, customerInfo,user.getTenantId());

        List<BaseEntity> messages = sqlManager.select(SQL + ".findMessageLimit", BaseEntity.class,map);
        JSONObject jsonObjec = new JSONObject();
        jsonObjec.put("id",sessionId);
        String avatar = "https://static.51sdx.com/p/html/kefu/yonghu.png";
        String name = "客户"+sessionId;
        if(customerInfo!=null){
            if(StringUtils.isNotBlank(customerInfo.getPhone())){
                name = customerInfo.getPhone();
            }
            if(StringUtils.isNotBlank(customerInfo.getWxPicurl())){
                avatar = customerInfo.getWxPicurl();
            }
        }
        jsonObjec.put("avatar",avatar);
        jsonObjec.put("name",name);
        jsonObjec.put("list",messages);
        List<JSONObject> list = new ArrayList<>();
        list.add(jsonObjec);
        return JsonResult.success(list);
    }

    /**
     * 初始化客户消息
     * @param request
     * @return
     */
    @RequestMapping("/initCusMsg.json")
    @ResponseBody
    public JsonResult initCusMsg(HttpServletRequest request) {
        JsonResult result = JsonResult.success();
        CoreUser user = getLoginUser(request);
        int userId = user.getId().intValue();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        CrmRepresentive crmRepresentive = sqlManager.selectSingle(SQL + ".findCrmRepByUserId", map, CrmRepresentive.class);
        if(crmRepresentive==null){
            crmRepresentiveService.insertCrmRepresentive(userId,user.getTenantId());
        }else{
            //修改坐席最后操作时间和状态
            crmChatService.updateCrmRepresentive(userId,"1,2");
        }
        List<CrmSession> crmSessionList = sqlManager.select(SQL + ".listCrmSession", CrmSession.class, map);

       if(crmSessionList.size()>0){
           List<JSONObject> list = new ArrayList<>();
           for (CrmSession crmSession : crmSessionList) {
               JSONObject jsonObject = resultJSON(crmSession.getOpenId(), crmSession.getSessionId(), crmSession.getCustomerId());
               list.add(jsonObject);
           }
           result = JsonResult.success(list);
       }else{
           result =  getJsonResult(user);
       }
        RepresentiveMessageScanner.startScanner(userId);
       return result;
    }

    public JSONObject resultJSON(String openId,int sessionId,String customerId){
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("openid", openId);
        CustomerInfo customerInfo = sqlManager.selectSingle(SQL + ".findCustomerInfo", map, CustomerInfo.class);

        List<BaseEntity> messages = sqlManager.select(SQL + ".findMessage", BaseEntity.class,map);

        JSONObject jsonObjec = new JSONObject();
        jsonObjec.put("id",sessionId);
        String avatar = "https://static.51sdx.com/p/html/kefu/yonghu.png";
        String name = "客户"+sessionId;
        if(customerInfo!=null){
            if(StringUtils.isNotBlank(customerInfo.getPhone())){
                name = customerInfo.getPhone();
            }
            if(StringUtils.isNotBlank(customerInfo.getWxPicurl())){
                avatar = customerInfo.getWxPicurl();
            }
        }
        jsonObjec.put("avatar",avatar);
        jsonObjec.put("name",name);
        jsonObjec.put("list",messages);
        return jsonObjec;
    }

    /**
     * 获取等待队列大小
     * @return
     */
    @PostMapping("/getWaitQueueSize.json")
    @ResponseBody
    public JsonResult getWaitQueueSize(HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        return JsonResult.success(redisService.listOpsSize("list" + WAIT_QUEUE + "_" + user.getTenantId()));
    }

    /**
     * 暂离
     * @param request
     * @return
     */
    @RequestMapping ("/leave.json")
    @ResponseBody
    public JsonResult leave(HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        int userId = user.getId().intValue();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        sqlManager.update(SQL+".updateCrmRepresentivePart",map);
        return JsonResult.success();
    }

    /**
     * 下线
     * @param request
     * @return
     */
    @RequestMapping ("/offline.json")
    public void offline(HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        int userId = user.getId().intValue();
        RepresentiveMessageScanner.stopScanner(userId);
    }


    /**
     * 聊天记录
     * @param id
     * @return
     */
    @RequestMapping("/chatLog.json")
    @ResponseBody
    public JsonResult getList(Integer id ) {
        CrmSession crmSession = new CrmSession();
        crmSession.setSessionId(id);
        CrmSession session = sqlManager.template(crmSession).get(0);

        Map<String, Object> map = new HashMap<>();
        map.put("customerId", session.getCustomerId());
        map.put("openid", session.getOpenId());
        CustomerInfo customerInfo = sqlManager.selectSingle(SQL + ".findCustomerInfo", map, CustomerInfo.class);
        List<CrmMessage> list = sqlManager.select(SQL + ".findMessage", CrmMessage.class,map);
        List<JSONObject>  jsonList = new ArrayList<>();
        for (CrmMessage message : list) {
            JSONObject json = new JSONObject();
            String username = "";
            String avatar = "";
            Integer chatId =null;
            if(message.getMsgClass()!=null&&message.getMsgClass()==2){
                username = "客服";
                avatar = "https://static.51sdx.com/p/html/kefu/kefu.png";
            }else{
                avatar = "https://static.51sdx.com/p/html/kefu/yonghu.png";
                username = "客户"+id;
                chatId = id;
                if(customerInfo!=null){
                    if(StringUtils.isNotBlank(customerInfo.getPhone())){
                        username = customerInfo.getPhone();
                    }
                    if(StringUtils.isNotBlank(customerInfo.getWxPicurl())){
                        avatar = customerInfo.getWxPicurl();
                    }

                }
            }
            json.put("avatar",avatar);
            json.put("username",username);
            json.put("id",chatId);
            json.put("content",message.getSafeContent());
            json.put("timestamp",message.getCreateTime().getTime());
            jsonList.add(json);
        }
        return JsonResult.success(jsonList);
    }

    /**
     * 查询客户订单信息
     * @param sessionId
     * @return
     */
    @RequestMapping ("/order.json")
    @ResponseBody
    public JsonResult order(Integer sessionId) {
        Map<String, Object> map = new HashMap<>();
        map.put("sessionId", sessionId);
        List<BaseEntity> list = sqlManager.select(SQL + ".selectOrder", BaseEntity.class,map);
        return JsonResult.success(list);
    }

    /**
     * 查询客户订单信息
     * @param sessionId
     * @return
     */
    @RequestMapping ("/getCust.json")
    @ResponseBody
    public JsonResult getCust(Integer sessionId) {
        Map<String, Object> map = new HashMap<>();
        map.put("sessionId", sessionId);
        BaseEntity baseEntity = sqlManager.selectSingle(SQL + ".selectCusInfo", map, BaseEntity.class);
        if(baseEntity.get("sex")!=null){
            Integer sex = Integer.parseInt(baseEntity.get("sex").toString());
            if(sex==1){
                baseEntity.set("sexStr","男");
            }else if(sex == 2){
                baseEntity.set("sexStr","女");
            }
        }
        if(baseEntity.get("majorType")!=null){
            Integer majorType = Integer.parseInt(baseEntity.get("majorType").toString());
            if(majorType==1){
                baseEntity.set("majorTypeStr","文科");
            }else if(majorType == 2){
                baseEntity.set("majorTypeStr","理科");
            }else if(majorType == 3){
                baseEntity.set("majorTypeStr","综合");
            }
        }

        if(baseEntity.get("choiceYear")!=null){
            Integer choiceYear = Integer.parseInt(baseEntity.get("choiceYear").toString());
            Calendar date = Calendar.getInstance();
            Integer year = Integer.valueOf(date.get(Calendar.YEAR));
            int diff = choiceYear - year;
            if(diff<=0){
                baseEntity.set("choiceYearStr",choiceYear+"年(高三)");
            }else if(diff==1){
                baseEntity.set("choiceYearStr",choiceYear+"年(高二)");
            }else if(diff==2){
                baseEntity.set("choiceYearStr",choiceYear+"年(高一)");
            }
        }
        return JsonResult.success(baseEntity);
    }

//    @RequestMapping ("/setNickName.json")
//    @ResponseBody
//    public JsonResult setNickName(HttpServletRequest request,String nickName) {
//        JsonResult result = JsonResult.success();
//        CoreUser user = getLoginUser(request);
//        CoreUser coreUser = new CoreUser();
//        coreUser.setId(user.getId());
//        coreUser.setNickName(nickName);
//        coreUser.setUpdateTime(new Date());
//        sqlManager.updateTemplateById(coreUser);
//        return result;
//    }
}
